package cn.com.shopec.erp.stock.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.taobao.api.internal.util.StringUtils;

import cn.com.shopec.erp.base.entity.LogisticsInfo;
import cn.com.shopec.erp.base.service.ILogisticInfoService;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.excel.ExcelBaseExport;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.JsonHelper2;
import cn.com.shopec.erp.common.utils.NoUtil;
import cn.com.shopec.erp.financing.entity.WhareHouse;
import cn.com.shopec.erp.financing.service.IWhareHouseServer;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrderReceiver;
import cn.com.shopec.erp.multiChannel.service.IChannelOrderService;
import cn.com.shopec.erp.multiChannel.vo.ChannelOrderVo;
import cn.com.shopec.erp.stock.commo.ObjectUtil;
import cn.com.shopec.erp.stock.commo.StockOutUtil;
import cn.com.shopec.erp.stock.commo.StockProductException;
import cn.com.shopec.erp.stock.entity.StockOut;
import cn.com.shopec.erp.stock.entity.StockOutProduct;
import cn.com.shopec.erp.stock.excel.impl.StockOutExcelExport;
import cn.com.shopec.erp.stock.service.IStockHistoryService;
import cn.com.shopec.erp.stock.service.IStockOutService;
import cn.com.shopec.erp.stock.vo.StockOutProductVo;
import cn.com.shopec.erp.stock.vo.StockOutVo;
import cn.com.shopec.erp.warehouse.entity.StockTransfer;
import cn.com.shopec.erp.warehouse.service.IStockTransferService;
import net.sf.json.JSONArray;

@Controller
@RequestMapping("stockmanage/StockController")
public class StockOutController {

	@Resource
	private IStockTransferService stockTransferService;
	
	@Resource
	private IStockHistoryService stockHistoryService;

	@Resource
	private IStockOutService stockOutService;

	@Resource
	private IWhareHouseServer iWhareHouseServer;

	@Resource
	private IChannelOrderService channelOrderService;

	 @Resource
     private ILogisticInfoService logisticInfoService;
	 
	/** 日志. */
	private Logger log = Logger.getLogger(StockOutController.class);

	/**
	 * 分页查询出库
	 * 
	 * @param stockOut
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("ajaxPageFinderStockOut")
	@ResponseBody
	public String ajaxPageFinderStockOutPackage(StockOutVo stockOut, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		PageFinder<StockOutVo> pageFinder = stockOutService.queryStockList(stockOut, pageQuery);
		jsonObj.put("Rows", pageFinder.getData());
		jsonObj.put("Total", pageFinder.getRowCount());
		return jsonObj.toJSONString();
	}
	
	/**
	 * 导出excel
	 * @param stockIn
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("exportStockOut")
	public void exportStockOutPackage(StockOutVo stockOut, HttpServletResponse response) throws Exception {
		List<StockOutVo> list = stockOutService.queryStockOutListByFinder(stockOut);
		ExcelBaseExport excelBaseExport = new StockOutExcelExport(list, "商品出库信息_" + System.currentTimeMillis(), response);
		try {
			excelBaseExport.wirteExcel();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 跳转到出库查询页面
	 * 
	 * @param stockOut
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("pageFinderStockOut")
	public String pageFinderStockOutPackage(StockOutVo stockOut, PageQuery pageQuery, ModelMap map) {
		map.put("whareHouse", iWhareHouseServer.getPagedCollectSetList(pageQuery).getData());
		map.put("stockOut", stockOut);
		return "/stock/stockOut_info_list";
	}

	/**
	 * 分页出库商品
	 * 
	 * @param stockOut
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("ajaxPageFinderStockOutDetail")
	@ResponseBody
	public String ajaxPageFinderStockOutDetailPackage(StockOutVo stockOut, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		PageFinder<StockOutProductVo> pageFinder = stockOutService.queryStockProductList(stockOut, pageQuery);
		jsonObj.put("Rows", pageFinder.getData());
		jsonObj.put("Total", pageFinder.getRowCount());
		return jsonObj.toJSONString();
	}

	/**
	 * 跳转到出库详细询页面
	 * 
	 * @param stockOut
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("toStockOutDetail")
	public String pageFinderStockOutDetailPackage(String stockOutNo, String tabId, PageQuery pageQuery, ModelMap map) {
		map.put("stockOut", stockOutService.getStockByNo(stockOutNo));
		map.put("stockOutViewType", SZSCMConstant.STOCK_INFO_VIEW);
		map.put("tabId", tabId);
		return "/stock/stockOut_detail";
	}

	/**
	 * 删除产品
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("deleteStockOutProduct")
	@ResponseBody
	public String deleteStockOutProduct(String id) {
		try {
			if (stockOutService.deleteStockOutProduct(id)) {
				return SZSCMConstant.SUCCESS;
			}
		} catch (Exception e) {
			log.error("deleteStockOutProduct" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 跳转到出库增加页面
	 * 
	 * @param stockOut
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("toStockOutAdd")
	public String toAddStockOut(String stockOutNo, String tabId, PageQuery pageQuery, ModelMap map) {
		map.put("stockOut", stockOutService.getStockByNo(stockOutNo));
		map.put("stockOutViewType", SZSCMConstant.STOCK_ADD_VIEW);
		map.put("tabId", tabId);
		return "/stock/stockOut_detail";
	}

	/**
	 * 增加出库信息
	 * @param stockOut
	 * @param products
	 * @param map
	 * @return
	 */
	@RequestMapping("addStockOut")
	@ResponseBody
	public String addStockOut(StockOut stockOut, String products, ModelMap map) {
		try {
			JSONArray jsonArray = JSONArray.fromObject(products);
			@SuppressWarnings("unchecked")
			List<StockOutProduct> stockOutProducts = (List<StockOutProduct>) JSONArray.toList(jsonArray,
					StockOutProduct.class);
			stockOutService.addStockOut(stockOut, stockOutProducts);
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("addStockOutfo" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 跳转到出库审核页面
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toStockOutApprove")
	public String toApproveStockOut(String stockOutNo, String tabId, PageQuery pageQuery, ModelMap map) {
		map.put("stockOutViewType", SZSCMConstant.STOCK_AUDIT_VIEW);
		map.put("stockOut", stockOutService.getStockByNo(stockOutNo));
		map.put("tabId", tabId);
		return "/stock/stockOut_detail";
	}

	/**
	 * 出库审核
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("approveStockOut")
	@ResponseBody
	public String approveStockOut(StockOutVo stockOutVo, String products, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		try {
			JSONArray jsonArray = JSONArray.fromObject(products);
			@SuppressWarnings("unchecked")
			List<StockOutProduct> stockOutProducts = (List<StockOutProduct>) JSONArray.toList(jsonArray,
					StockOutProduct.class);
			stockOutService.approveStockOut(stockOutVo,stockOutProducts);
			jsonObj.put("result", SZSCMConstant.SUCCESS);
		}catch(StockProductException stockProductException){
			jsonObj.put("result", SZSCMConstant.FAIL);
			jsonObj.put("resultMsg", stockProductException.getExceptionInfo());
		} catch (Exception e) {
			log.error("approveStockOut" + e.getMessage(), e);
			jsonObj.put("result", SZSCMConstant.FAIL);
		}
		return jsonObj.toJSONString();
	}

	/**
	 * 跳转包裹单出库或包裹单换货出库单新增页面
	 * 
	 * @param channelOrderId
	 * @param prodPackageNo
	 * @param tabId
	 * @param map
	 * @return
	 */
	@RequestMapping("toPackageStockOut")
	public String toPackageStockOut(String orderReturnType,String channelOrderId, String prodPackageNo, String tabId, ModelMap map) {
		try {
			ChannelOrderReceiver channelOrderReceiver = channelOrderService.getChannelOrderReceiver(channelOrderId);
			StockOutVo stockOut = StockOutUtil.parseStockOutProduct(channelOrderReceiver);
			stockOut.setStockOutNo(NoUtil.getNo(NoUtil.STOCKOUT_NO));
			if(StringUtils.isEmpty(orderReturnType)){
				map.put("stockOutViewType", SZSCMConstant.STOCK_PACKAGE_VIEW);//普通包裹单出库
				stockOut.setStockOutType(SZSCMConstant.STOCKOUT_TYPE_1);
				stockOut.setStockOutTypeNo(prodPackageNo);
			}else{
				map.put("stockOutViewType", SZSCMConstant.STOCK_PACKAGE_RETURN_VIEW);//换货包裹单出库
				stockOut.setStockOutTypeNo(channelOrderId);
				stockOut.setStockOutType(SZSCMConstant.STOCKOUT_TYPE_4);
			}
			map.put("stockOut", stockOut);
		} catch (Exception e) {
			log.error("approveStockOut" + e.getMessage(), e);
		}
		map.put("tabId", tabId);
		return "/stock/stockOut_detail";
	}

	/**
	 * 获取包裹单商品，并转成出库单商品返回
	 * 
	 * @param channelOrderVo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("getPackageProduct")
	@ResponseBody
	public String getPackageProduct(ChannelOrderVo channelOrderVo, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		if (!StringUtils.isEmpty(channelOrderVo.getProdPackageNo())) {
			@SuppressWarnings("unchecked")
			PageFinder<Map<String, Object>> pageFinder = channelOrderService.productPackageItemPageList(channelOrderVo,
					pageQuery);
			List<StockOutProductVo> stockOutProductVo = StockOutUtil.parseStockOutProductVo(pageFinder.getData());
			jsonObj.put("Rows", stockOutProductVo);
			jsonObj.put("Total", pageFinder.getRowCount());
		}
		return jsonObj.toJSONString();
	}
	
	/**
	 * 跳转调拨出库单新增页面
	 * 
	 * @param channelOrderId
	 * @param prodPackageNo
	 * @param tabId
	 * @param map
	 * @return
	 */
	@RequestMapping("toTransferStockOut")
	public String toTransferStockOut(StockTransfer stockTransfer ,String tabId,ModelMap map) {
		try {
			StockOutVo stockOut = new StockOutVo();
			stockOut.setStockOutNo(NoUtil.getNo(NoUtil.STOCKOUT_NO));
			stockOut.setStockOutType(SZSCMConstant.STOCKOUT_TYPE_5);
			stockOut.setStockOutTypeNo(stockTransfer.getTransferNo());
			WhareHouse whareHouse= iWhareHouseServer.getWhareHouseByNo(stockTransfer.getTransferInWhNo());
			if(ObjectUtil.isNotNull(whareHouse)){
				stockOut.setReceiverName(whareHouse.getWhUser());
				stockOut.setReceiverTel(whareHouse.getWhPhone());
				stockOut.setReceiverAddr(whareHouse.getWhAdderss());
			}
			map.put("stockOut", stockOut);
			map.put("stockTransfer", stockTransfer);
			map.put("stockOutViewType", SZSCMConstant.STOCK_TRANSFER_OUT_VIEW);
		} catch (Exception e) {
			log.error("approveStockOut" + e.getMessage(), e);
		}
		map.put("tabId", tabId);
		return "/stock/stockOut_detail";
	}
	
	/**
	 * 跳转到物流查询页面
	 * 
	 * @param channelOrderVo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("logisticsSelect")
	public String toLogisticsPage(LogisticsInfo logisticsInfo, PageQuery pageQuery, ModelMap map) {

        PageFinder<LogisticsInfo> pageFinder =  logisticInfoService.getPageFinderLogisticInfo(logisticsInfo, pageQuery);
        String json = JsonHelper2.toJson(pageFinder.getData());
        map.put("rows", json);
        map.put("total", pageFinder.getData().size());
        map.put("LogisticsInfo", logisticsInfo);
		return "/stock/logistics_select";
	}
}
